<script>
import { defineComponent, ref, nextTick, onMounted,onUnmounted } from '@vue/composition-api';
import {
  listOrg,
} from '@/api/organ/studentOrgan';
import {
  GetActivityList,
  GetActivityDetail,
  addActs,
  ToggleTopActivity,
  deleteActivity,
  exportActivity,
  showQrCode,
  scanningQrCode,
  downloadImgs,
} from '@/api/activity';
import {
  ActivityStatusOptions,
  ActivityStatusMap,
  ActivityContentOptions,
  ActivityContentMap,
  TypeMaps
} from '../enum';
import { MessageBox, Message } from 'element-ui';
import router from '@/router';
import { download } from '@/utils/request';
import { mapGetters } from 'vuex';
import processApi from "@/api/workflow/processInst";
import history from "@/components/Process/History";
import verify from "@/components/Process/Verify";
let timer;
export default defineComponent({
  name: 'ActivityList',
  computed: {
    ...mapGetters(['roles', 'name', 'userName']),
  },
  components: {
    history,
    verify
  },
  props: {
    createdBy: {
      type: String,
      default: '',
    },
    unitName: {
      type: String,
      default: '',
    },
  },
  setup(props) {
    const managerType = ref();
    const loading = ref(false);
    const isCanRead = ref(false);
    const list = ref([]);
    const pageNum = ref(1);
    const pageSize = ref(10);
    const total = ref(0);
    const studentId = ref(props.createdBy);
    const seminarInfo = ref();
    const addForm = ref({});

    const formRef = ref();
    const activityId = ref('');
    const formModel = ref({ activityName: '', activityContent: '' });

    const activityContent = ref('');
    const QRCodeImage = ref('');
    const QRCode = ref(false);
    const openAdd = ref(false);
    const title = ref('');
    const title1 = ref('增加活动人数');
    const QRCodeValue = ref('');
    const codeName = ref(['工作人员', '选手码', '补录码']);

    const processInstanceOpen = ref(false);
    const processInstanceId = ref('');
    const taskVariables = ref({}); //流程变量
    const taskId = ref(); //任务id

    const loadData = async () => {
      loading.value = true;
      console.log(props.createdBy, 'props.createdBy');
      console.log(managerType.value, 'managerType');
      var actCon = null;
      const payload = {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        activityType:1,
        ...formModel.value,
      };

      const response = await GetActivityList(payload);
      loading.value = false;
      if (response.code === 200) {
        const { rows, total: rowTotal } = response;
        list.value = rows;
        console.log(rows, 'rows');
        total.value = rowTotal;
      }
    };
    const getSeminarInfo = async () => {
      const payload = {
        pageNum: 1,
        pageSize: 10,
        orgName: "杭州电子科技大学青协",
        type: 4,
        orgType: 4,
      };

      const response = await listOrg(payload);
      if (response.code === 200) {
        seminarInfo.value = response.rows[0];
        console.log(seminarInfo.value, "seminarInfo.value")
      }
    };
    const refresh = () => {
      pageNum.value = 1;
      loadData();
    };

    const reset = formEl => {
      formEl.resetFields();
      formModel.value.activityContent = ''
      refresh();
    };

    const create = () => {
      // let managerType = managerType.value;
      router.push({ path: '/activity/createActivity', query: { studentId, managerType: managerType.value } });
    };
    const addAct = activityIds => {
      // let managerType = managerType.value;
      // console.log(activityIds);
      activityId.value = activityIds
      // console.log(activityId.value);
      openAdd.value = true
    };

    const activityDetail = activityId => {
      router.push({ path: '/activity/activity-detail/index/' + activityId, query: { managerType: managerType.value } });
    };

    const editActivity = (activityId, type) => {
      // let managerType = managerType.value;
      router.push({ path: '/activity/createActivity', query: { activityId, type, studentId, managerType: managerType.value } });
    };

    const delActivity = (activityId, activityName) => {
      MessageBox.confirm(`确认删除活动【${activityName}】?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        const response = await deleteActivity(activityId);
        if (response.code === 200) {
          Message({
            message: '删除活动成功',
            type: 'success',
          });
          loadData();
        }
      });
    };
    // 活动置顶
    const activityTop = (activityId, type) => {
      MessageBox.confirm(`${!type ? '取消' : ''}置顶活动?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        const response = await ToggleTopActivity(activityId);
        if (response.code === 200) {
          Message({
            message: '置顶活动成功',
            type: 'success',
          });
          loadData();
        }
      });
    };
    // 审批历史
    const activityProcess = async (activityId) => {
      processInstanceOpen.value = false;
      const response = await GetActivityDetail(activityId);
      if (response.code === 200) {
        // formModel.value = response.data;
        nextTick(() => {
          processInstanceId.value = response.data.actBusinessStatus.processInstanceId;
          if (response.data.actBusinessStatus.processInstanceId) {
            processInstanceOpen.value = true;
          } else {
            Message({
              message: '未开启过流程！',
              type: 'warning',
            });
          }
        })
      }
    };
    /** 5.二维码 */
    const code = async row => {
      console.log(row, 'row');
      title.value = row.activityName + ' 活动报名';
      const response = await showQrCode(row.activityId);
      if (response.code == 200) {
        // Message({
        //   message: '二维码已生成',
        //   type: 'success',
        // });
        QRCodeImage.value = response.msg;

        QRCode.value = true;
      }
    };
    // 下载二维码
    const openUrl = (fileName, title) => {
      const dataurl = document.getElementById('erCode').src//选择图片id
      // this.downloadBase64(dataurl, this.erCode_name)
      const a = document.createElement('a')
      a.href = dataurl
      a.download = title + '.jpg';
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
    };
    // 签到二维码
    const signCode = (role, row) => {
      console.log(row.activityName, row.activityId, role);
      getCodeImg(row.activityName, row.activityId, role);
      timer = setInterval(function () { getCodeImg(row.activityName, row.activityId, role); }, 10000);
      // this.getNumCode()getCodeImg
    };
    const closeQRCode = () => {
      clearInterval(timer);
      timer = null;
    };
    /** 5.二维码 */
    const getCodeImg = async (activityName, activityId, role) => {
      const response = await scanningQrCode(activityId, role);
      if (response.code == 200) {
        console.log(activityName, "activityName")
        if (role == 4) {
          title.value = activityName + " " + (response.data.type == 1 ? "签到码" : "签退码");
        } else {
          title.value = activityName + " " + codeName.value[role - 1];
        }

        QRCodeImage.value = response.data.qrCode;
        QRCodeValue.value = response.data.signCode;
        QRCode.value = true;
      } else {
        clearInterval(timer);
        timer = null;
        QRCode.value = false;
      }
    };
    // 导出活动信息按钮
    const exportActivityInfo = () => {
      download(
        'committee/activity/export',
        {
          created_by: studentId.value,
        },
        `activity_${new Date().getTime()}.xlsx`
      );
    };
    // 导出人员名单按钮
    const exportActivityDetail = () => {
      download(
        'committee/activity/exportdetail',
        {
          created_by: studentId.value,
        },
        `personnel_${new Date().getTime()}.xlsx`
      );
    };
    const canRead = (roles, item) => {
      var isCanRead = false;

      if (roles) {
        for (let i = 0; i < roles.length; i++) {
          if (['admin', 'common'].includes(roles[i])) {
            isCanRead = true;
            break;
          } else if (['guiding-unit', 'teacher3'].includes(roles[i])) {
            console.log(props.unitName, "unitName")
            if (props.unitName == item.hostName) {
              isCanRead = true;
              break;
            }
          }
          // else if (name == this.orgForm.teacherId || name == this.orgForm.studentId) {
          //   isCanRead = true;
          //   break;
          // }
        }
      }
      console.log(isCanRead, 'isCanRead');
      // isCanRead.value = isCanRead;
      return isCanRead;
    };

    onMounted(() => {
      managerType.value = router.history.current.query.managerType;
      if (managerType.value == 'seminar') {
        getSeminarInfo();
      }
      loadData();
    });
    onUnmounted(() => {
      clearInterval(timer);
        timer = null;
    });
    // onUnmounted(() => {
    //   if (timer) clearInterval(timer)
    // });
    // 确定添加
    const sureAdd = async () => {
      console.log(addForm.value.applyCount);
      const payload = {
        applyCount: addForm.value.applyCount,
        activityId: activityId.value
      }
      const response = await addActs(payload);
      if (response.code == 200) {
        Message({
          message: '修改成功',
          type: 'success',
        });
        openAdd.value = false
      } else {
        openAdd.value = true
      }

    }
    // 取消添加
    const cancleAct = () => {
      openAdd.value = false
      addForm.value = {}
    }

    return {
      managerType,
      formRef,
      formModel,
      loadData,
      reset,
      refresh,
      activityId,
      create,
      activityDetail,
      editActivity,
      addAct,
      cancleAct,
      delActivity,
      activityTop,
      activityProcess,
      code,
      loading,
      canRead,
      isCanRead,
      list,
      total,
      pageNum,
      pageSize,
      exportActivityInfo,
      exportActivityDetail,
      ActivityStatusOptions,
      ActivityStatusMap,
      activityContent,
      ActivityContentOptions,
      ActivityContentMap,
      QRCodeImage,
      signCode,
      closeQRCode,
      getCodeImg,
      QRCode,
      title,
      title1,
      QRCodeValue,
      codeName,
      processInstanceOpen,
      processInstanceId,
      taskVariables, //流程变量
      taskId, //任务id
      openAdd,
      openUrl,
      getSeminarInfo,
      seminarInfo,
      addForm,
      sureAdd,
      TypeMaps
    };
  },
});
</script>

<template>
  <div class="app-container">
    <!-- <el-row>
      <el-tabs v-model="activityContent" type="card" @tab-click="refresh">
        <el-tab-pane label="全部活动" name="0" />
        <el-tab-pane
          v-for="item in ActivityContentOptions"
          :label="item.label"
          :name="item.value"
          :key="item.item"
        />
      </el-tabs>
    </el-row> -->
    <el-row>
      <el-form ref="formRef" :model="formModel" inline size="mini">
        <el-form-item label="活动名称" prop="activityName">
          <el-input v-model="formModel.activityName" placeholder="请输入关键词" />
        </el-form-item>
        <el-form-item label="活动类型" prop="activityType">
          <el-select v-model="formModel.activityContent" placeholder="请选择类型">
            <el-option v-for="item in ActivityContentOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="状态" prop="activityStatus">
          <el-select v-model="formModel.activityStatus" placeholder="请选择状态">
            <el-option v-for="item in ActivityStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" size="mini" @click="loadData">查询</el-button>
          <el-button type="primary" size="mini" @click="reset(formRef)">重置</el-button>
          <el-button v-hasPermi="['activity:manager:create']" type="primary" size="mini" @click="create">创建活动</el-button>
          <el-button v-if="managerType == 'seminar' && (seminarInfo.teacherId == name || seminarInfo.studentId == name)"
            type="primary" size="mini" @click="create">创建活动</el-button>
          <el-button v-if="createdBy" type="primary" size="mini" @click="exportActivityInfo">导出活动信息</el-button>
          <el-button v-if="createdBy" type="primary" size="mini" @click="exportActivityDetail">导出人员名单</el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <el-row>
      <el-table v-loading="loading" :data="list" border>
        <el-table-column label="活动名称" align="center" fixed prop="activityName" />
        <el-table-column label="发起单位" align="center" prop="hostName" />
        <el-table-column label="创建时间" align="center">
          <template slot-scope="scope">
            {{ scope.row.nickName == '若依' ? 'admin' : scope.row.nickName }}
            <br />
            {{ scope.row.createdTime }}
          </template>
        </el-table-column>
        <el-table-column label="活动类型" align="center" prop="activityContent">
          <template slot-scope="scope">
            {{ TypeMaps.get(scope.row.activityContent) }}
          </template>
        </el-table-column>
        <el-table-column label="报名截止时间" align="center" prop="applyEndTime" />
        <el-table-column label="状态" align="center" prop="activityStatus">
          <template slot-scope="scope">
            {{ scope.row.activityStatusName }}
            <el-tag type="success" v-if="scope.row.sorted === 99">置顶</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="活动举办时间" align="center">
          <template slot-scope="scope">
            {{ scope.row.activityStartTime }}
            <br />
            {{ scope.row.activityEndTime }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="300">
          <template slot-scope="scope">
            <el-button type="primary" v-hasPermi="['activity:manager:index']" size="mini"
              @click="activityDetail(scope.row.activityId)">
              详情
            </el-button>
            <el-button type="primary" size="mini"
              v-if="['1', '2'].includes(scope.row.activityStatus) && (name == scope.row.createdBy || name == scope.row.adminId || name == scope.row.adminId2)"
              @click="editActivity(scope.row.activityId, 1)">
              修改
            </el-button>
            <el-button type="warning" size="mini" v-if="scope.row.sorted === 99" v-hasPermi="['activity:manager:top']"
              @click="activityTop(scope.row.activityId, 0)">取消置顶</el-button>
            <el-button type="warning" size="mini" v-else v-hasPermi="['activity:manager:top']"
              @click="activityTop(scope.row.activityId, 1)">置顶</el-button>
            <!-- <el-button type="warning" size="mini" @click="activityProcess(scope.row.activityId)">审批历史</el-button> -->
            <el-button size="mini" type="success" @click="code(scope.row)">二维码</el-button>
            <el-button style="margin: 10px" type="danger" size="mini" v-hasPermi="['activity:manager:del']"
              @click="delActivity(scope.row.activityId, scope.row.activityName)">
              删除
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="签到码" align="center" fixed="right" width="200">
          <template slot-scope="scope">
            <div
              v-if="['4', '5'].includes(scope.row.activityStatus) && (name == scope.row.createdBy || name == scope.row.adminId || name == scope.row.adminId2)">
              <el-button type="primary" size="mini" v-for="(item1, index) in codeName" :key="index"
                style="margin-bottom:10px" @click.stop='signCode(index + 1, scope.row)'>
                {{ item1 }}
              </el-button>
              <el-button type="primary" size="mini" @click.stop='signCode(4, scope.row)'>
                {{ scope.row.type == 1 ? "签到码" : "签退码" }}
              </el-button>

            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="pageNum" :limit.sync="pageSize" @pagination="loadData" />
    </el-row>
    <!-- 二维码对话框 -->
    <el-dialog :title="title" :visible.sync="QRCode" width="380px" append-to-body @close="closeQRCode">
      <el-card>
        <el-image id="erCode" v-if="QRCodeImage" style="width: 300px; height: 300px" :src="QRCodeImage"
          :preview-src-list="[QRCodeImage]" fit="cover">
        </el-image>
        <el-button type="primary" v-if="!QRCodeValue" @click="openUrl(QRCodeImage, title)">点击下载</el-button>
        <el-button type="primary" plain v-if="QRCodeValue">{{ QRCodeValue }}</el-button>
      </el-card>
    </el-dialog>
    <!-- 添加活动人数对话框 -->
    <el-dialog :title="title1" :visible.sync="openAdd" width="450px" append-to-body>
      <el-form :model="addForm">
        <el-form-item label="修改最大报名人数">
          <el-input placeholder="请输入最大报名人数" v-model="addForm.applyCount" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancleAct">取 消</el-button>
        <el-button type="primary" @click="sureAdd">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 审批对话框 -->
    <el-dialog title="审批历史" :visible.sync="processInstanceOpen" width="1200px" append-to-body>
      <!-- 审批历史 -->
      <history ref="historyRef" v-if="processInstanceOpen" :processInstanceId="processInstanceId"></history>
    </el-dialog>
  </div>
</template>
